package com.malphi.framework.flash.jsonparse;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * flash 发送的请求数据解析成可执行方法
 * @author mrf
 *
 */
public class FlashRequestParser {
	private static final String METHOD = "method";
	private static final String PARAM = "params";
	private static final String PARAM_TYPE = "type";
	private static final String PARAM_VALUE = "value";
	
	/**
	 * 从flash回传数据解析成要执行的方法列表
	 * flash json 格式:
	 * [
	 * 	  {"method":methodName,
	 *     "params":[{"type":typeCode,"value":value},{},...]
	 *    },
	 *    {},
	 *    ... 
	 * ]
	 * @param data
	 * @return
	 */
	public static List<InvocationMethod> getJsonData(String data){
		JSONArray methodArray = JSONArray.fromObject(data);
		return buildMethods(methodArray);
	}
	
	private static List<InvocationMethod> buildMethods(JSONArray methodArray){
		if(methodArray==null) return Collections.emptyList();
		List<InvocationMethod> list = new ArrayList<InvocationMethod>();
		for (int i = 0; i < methodArray.size(); i++) {
			JSONObject jsonMethod = methodArray.getJSONObject(i);
			String name = jsonMethod.getString(METHOD);
			List<InvocationParam> params = buildParams(jsonMethod.getJSONArray(PARAM));
			InvocationMethod method = new InvocationMethod(name, params);
			list.add(method);
		}
		return list;
	}
	private static List<InvocationParam> buildParams(JSONArray paramArray){
		if(paramArray==null) return Collections.emptyList();
		List<InvocationParam> list = new ArrayList<InvocationParam>();
		for (int i = 0; i < paramArray.size(); i++) {
			JSONObject paramObject = paramArray.getJSONObject(i);
			InvocationParam param = new InvocationParam(paramObject.getInt(PARAM_TYPE),
					                                    paramObject.get(PARAM_VALUE));
			list.add(param);
		}
		return list;
	}
	
	public static void main(String[] args) {
		String data = "[{\"method\":\"foo\",\"params\":[{\"type\":1,\"value\":1},{\"type\":2,\"value\":\"a\"}]}" +
				"       ,{\"method\":\"fff\",\"params\":[{\"type\":11,\"value\":11},{\"type\":2,\"value\":\"bb\"}]} ]";
		List<InvocationMethod> list = getJsonData(data);
		for (InvocationMethod invocationMethod : list) {
			System.out.println(invocationMethod);
		}
		
	}

}
